<!--
 * @Author       : tg
 * @LastEditors  : wfl
 * @description  : 选择标签
 * @updateInfo   :
 * @Date         : 2023-08-14 11:04:34
 * @LastEditTime : 2023-11-21 11:43:37
-->
<script lang="ts" setup name="GlCommonGroup">
// 登录信息
import { organizaApi } from '@/MainApp/apis/organiza'
const props = defineProps({
  visibleShow: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '选择标签'
  }
})
const emits = defineEmits<{
  (event: 'cancel'): void
  (event: 'confirm'): void
  (event: 'handleSelectionChange', array: any): void
}>()
const AddCommonGroup = defineAsyncComponent(() => import('./AddCommonGroup.vue'))
const { msgError, msgBoxWarnAsync, msgSuccess } = useMessage()

// 显示弹框
const visibleShow = ref(props.visibleShow)
watch(
  () => props.visibleShow,
  bool => {
    visibleShow.value = bool
  }
)
const listData = ref([] as any)
// 打开弹框
const handOpen = () => {
  listData.value = []
  // 请求数据
  apiForm()
}
const tableData = ref([]) // 数据
const countTotal = ref(0) // 分页条数
// 多选
const handleSelectionChange = (val: any) => {
  listData.value = val
}

const { attrs }: { attrs: any; } = getCurrentInstance()!
const page = ref({
  page: attrs.page?.page || 1,
  rows: 15,
  name: ''
})
// 数据接口
const apiForm = async () => {
  const params = {
    ...page.value // 分页参数
  }
  const res = await organizaApi.listPage(params)
  if (res.success) {
    tableData.value = res.data // 数据
    countTotal.value = res.total // 总条数
  }
  else { msgError(res.msg) }
}
// 通过标签名称查询
const inputBlur = (val: any) => {
  page.value.name = val
  apiForm()
}
// 关闭取消
const handCancel = () => {
  emits('cancel')
}

// 分页修改
const handSearchPage = (val: any) => {
  page.value = val
  apiForm()
}
// 添加常用组 edit--编辑 look 查看呢
const visibleShowAddCommonGroup = ref(false)
const addCommonGroupTitle = ref('')
const editCommonGroup: any = ref(null)
const addCommonGroup = (val: string, row: any) => {
  addCommonGroupTitle.value = val
  visibleShowAddCommonGroup.value = true
  if (val !== 'add' && row)
    editCommonGroup.value = row
}
// 删除常用组
const deletCommonGroup = async (name: any, row?: any) => {
  if (name === 'one') {
    // 单个删除
    msgBoxWarnAsync('确认删除', `删除后，此标签【${row.name}】将被删除，无法恢复！`, async () => {
      const { msg, success } = await organizaApi.labelDelete(row.id)
      if (success) {
        msgSuccess(msg)
        apiForm()
      }
      else { msgError(msg) }
    })
  }
  else {
    // 批量删除
    if (listData.value.length === 0) {
      msgError('请选择标签')
      return
    }
    const ids: any[] = []
    listData.value.forEach((item: { id: any; }) => {
      ids.push(item.id)
    })
    const { msg, success } = await organizaApi.batchDelete(ids)
    if (success) {
      msgSuccess(msg)
      apiForm()
    }
    else { msgError(msg) }
  }
}

// 选择组织返回
const confirmCommonGroup = () => {
  apiForm()
  visibleShowAddCommonGroup.value = false
}
const loading = ref(false)
// 确认选择
const handConfirm = () => {
  const res = new Map()
  const list = listData.value
  const dataList = list.filter((list: { id: any; }) => !res.has(list.id) && res.set(list.id, 1))
  emits('handleSelectionChange', dataList)
}
</script>

<template>
  <GlDialog
    v-if="!visibleShowAddCommonGroup"
    :visible="visibleShow"
    destroy-on-close
    :width="900"
    :title-header="title"
    @handOpen="handOpen"
  >
    <template #dialogForm>
      <el-input
        v-model="page.name"
        clearable
        placeholder="输入关键字，回车搜索"
        @input="inputBlur"
      />
      <el-table
        :data="tableData"
        height="500px"
        style="width: 100%; margin-top: 16px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号" />
        <el-table-column prop="name" label="标签名称" />
        <el-table-column prop="organizations" label="关联组织数" width="120">
          <template #default="scope">{{ scope.row.organizations.length > 0 ? scope.row.organizations.length : 0 }}</template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="150">
          <template #default="scope">
            <el-button type="text" link @click="addCommonGroup('rename', scope.row)"><i class="iconfont icon-huamingce"></i></el-button>
            <el-button type="primary" link @click="addCommonGroup('edit', scope.row)"><i class="iconfont icon-icon_redact"></i></el-button>
            <el-button type="danger" link @click="deletCommonGroup('one', scope.row)"><i class="iconfont icon-Icon_delete"></i></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <IkPage
        v-if="countTotal"
        :current="($attrs as any)?.page?.page || 1"
        :total="countTotal"
        :search="handSearchPage"
      />
    </template>
    <template #bottomBtn>
      <div class="form-footer">
        <div>
          <el-button @click="addCommonGroup('add', null)"><i class="iconfont icon-icon_add" style="margin-right: 5px;font-weight: 600;font-size: 12px;"></i>新增标签</el-button>
          <el-button type="danger" plain @click="deletCommonGroup('more', '')">
            <i class="iconfont icon-Icon_close" style="margin-right: 5px;font-weight: 600;font-size: 12px;"></i>
            批量删除
          </el-button>
        </div>
        <span class="dialog-footer">
          <el-button bg text @click="handCancel">取消</el-button>
          <el-button
            v-loading="loading"
            bg
            type="primary"
            @click="handConfirm"
          >
            确认选择
          </el-button>
        </span>
      </div>
    </template>
  </GlDialog>
  <AddCommonGroup
    :visible-show="visibleShowAddCommonGroup"
    :header="addCommonGroupTitle"
    :edit="editCommonGroup"
    @cancel="confirmCommonGroup"
    @confirm="confirmCommonGroup"
  />
</template>

<style lang="scss" scoped>
.form-footer{
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
